<?php
function create_header($config,$lang,$cats=array(),$page_title='')
{
	$current_parent = '0';
	
	if(isset($_GET['i']))
	{
		if($cats[$_GET['i']]['parent_id'] == '0')
		{
			if($cats[$_GET['i']]['cat_subs'] == '0')
			{
				$current_parent = 0;
			}
			else
			{
				$current_parent = $_GET['i'];
			}
		}
		else
		{
			$current_parent = $cats[$_GET['i']]['parent_id'];
		}
	}

	$maincats = array();
	$subcats = array();
	$curcats = array();
	$subcount = 0;
	
	foreach ($cats as $key => $value)
	{
		if($value['parent_id'] == 0)
		{
			$maincats[] = $value;
		}
		else
		{
			$subcats[] = $value;
			
			if($value['parent_id'] == $current_parent)
			{
				$curcats[] = $value;
				$subcount++;
			}
		}
	}

	$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/overall_header.html");
	$page->SetLoop('CATS',$cats);
	$page->SetLoop('CATS_MAIN',$maincats);
	$page->SetLoop('CATS_SUB',$subcats);
	$page->SetLoop('CATS_CUR',$curcats);
	$page->SetParameter('SUBCAT_COUNT',$subcount);
	$page->SetParameter('SITE_TITLE', $config['site_title']);
	$page->SetParameter('PAGE_TITLE', $page_title);
	$page->SetParameter('TPL_NAME', $config['tpl_name']);
	$page->SetParameter('SITE_URL', $config['site_url']);
	$page->SetParameter('ANOUNCE',$config['anounce_en']);
	$page->SetParameter('ANOUNCE_TEXT',$config['anounce_txt']);
	$page->SetParameter('CURRENT_PARENT',$current_parent);
	
	if(isset($_SESSION['duser']['id']))
	{
		$page->SetParameter('LOGGED_IN', 1);
	}
	else
	{
		$page->SetParameter('LOGGED_IN', 0);
	}
		
	return $page->CreatePageReturn($lang,$config);
}

function create_footer($config,$lang)
{
	$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/overall_footer.html");
	$page->SetParameter('VERSION',$config['version']);
	return $page->CreatePageReturn($lang,$config);
}

function db_connect($config)
{
    $db_connection = @mysql_connect ($config['db']['host'], $config['db']['user'], $config['db']['pass']) OR error (mysql_error(),$config, __LINE__, __FILE__, 0, '');
    $db_select = @mysql_select_db ($config['db']['name']) or error (mysql_error(),$config, __LINE__, __FILE__, 0, '');
	
	return $db_connection;
}

function error($msg,$config, $line='', $file='', $formatted=0,$lang=array())
{
	IF($formatted == 0)
	{
		echo "Low Level Error: " . $msg;
	}
	ELSE
	{
		$page = new HtmlTemplate ("templates/" . $config['tpl_name'] . "/error.html");
		$page->SetParameter ('MESSAGE', $msg);
		$page->CreatePageEcho($lang);
	}
	exit;
}

function logincheck($redirect='')
{
	if(!isset($_SESSION['duser']['id']))
	{
		if($redirect)
		{
			header("Location: ".$config['site_url']."login.php?redirect=".urlencode($redirect));
		}
		else
		{
			header("Location: ".$config['site_url']."login.php");
		}
		exit;
	}
}

function checkinstall($config)
{
	if(!isset($config['installed']))
	{
		header("Location: install/");
		exit;
	}
}

function checkremember($config)
{
	if(!isset($_SESSION['duser']['id']))
	{
		if(isset($_COOKIE[$config['cookie_name']]))
		{
			$remarray = unserialize(str_replace('\\','',$_COOKIE[$config['cookie_name']]));
			
			// Lookup the users table for that user
			$user_info = mysql_fetch_row(mysql_query("SELECT user_id,remember,commentst FROM ".$config['db']['pre']."users WHERE username='".validate_input($remarray['username'])."' AND user_id='".validate_input($remarray['uid'])."' AND remember='".validate_input($remarray['rem'])."' LIMIT 1"));

			// The submitted details are valid
			if(isset($user_info[0]))
			{		
				$_SESSION['duser']['id'] = $user_info[0];
				$_SESSION['duser']['name'] = $remarray['username'];
				$_SESSION['duser']['comm'] = $user_info[2];
		
				header('Location: index.php');
				exit;
			}
		}
	}
}

function get_cats($config,$lang=array())
{
	// Initiate the Category array
	$cats = array();
	$cats2 = array();
	$parents = array();
	$sort = array();
	$count = 0;
	
	$cats[0]['cat_title'] = $lang['VIEWALL'];
	$cats[0]['cat_id'] = 0;
	$cats[0]['parent_id'] = 0;
	$cats[0]['cat_subs'] = 0;
	if($config['mod_rewrite'] == 1)
	{
		$cats[0]['cat_url'] = $config['site_url'].'viewall/1.html';
	}
	else
	{
		$cats[0]['cat_url'] = $config['site_url'].'index.php';
	}
	
	$query = "SELECT cat_id,cat_title,parent_id,cat_subs FROM ".$config['db']['pre']."cats ORDER BY cat_title";
	$query_result = @mysql_query ($query) OR error(mysql_error(), __LINE__, __FILE__, 0, '', '');
	while ($info = @mysql_fetch_array($query_result))
	{
		$cats2[$info['parent_id']][$info['cat_id']] = $info;
		$cats2[$info['parent_id']][$info['cat_id']]['cat_title'] = stripslashes($info['cat_title']);
		if($config['mod_rewrite'] == 1)
		{
			$cats2[$info['parent_id']][$info['cat_id']]['cat_url'] = $config['site_url'].'view/'.$info['cat_id'].'/'.modrewriteurl($info['cat_title']).'/1.html';
		}
		else
		{
			$cats2[$info['parent_id']][$info['cat_id']]['cat_url'] = $config['site_url'].'cat.php?id='.$info['cat_id'];
		}
		
		if(isset($parents[$info['parent_id']]))
		{
			$parents[$info['parent_id']]++;
		}
		else
		{
			$parents[$info['parent_id']] = 0;
		}
		
		if($info['parent_id'] == 0)
		{
			$sort[$count] = $info['cat_id'];
			$count++;
		}
	}
	
	$count = 1;
	foreach ($sort as $key => $value)
	{
		$cats[$value] = $cats2[0][$value];
		unset($cats2[0][$value]);
		$count++;
		
		if(isset($cats2[$value]))
		{
			$cats[$value]['cats'] = count($cats2[$value]);
			foreach ($cats2[$value] as $key2 => $value2)
			{
				$cats[$key2] = $value2;
				unset($cats2[$value][$key2]);
				$count++;
			}
		}
	}
	
	return $cats;
}

function pagenav($total,$page,$perpage,$url,$posts=0,$lang=array()) 
{
	$page_arr = array();
	$arr_count = 0;

	if($posts) 
	{
		$symb='&';
	}
	else
	{
		$symb='?';
	}
	$total_pages = ceil($total/$perpage);
	$llimit = 1;
	$rlimit = $total_pages;
	$window = 5;
	$html = '';
	if ($page<1 || !$page) 
	{
		$page=1;
	}
	
	if(($page - floor($window/2)) <= 0)
	{
		$llimit = 1;
		if($window > $total_pages)
		{
			$rlimit = $total_pages;
		}
		else
		{
			$rlimit = $window;
		}
	}
	else
	{
		if(($page + floor($window/2)) > $total_pages) 
		{
			if ($total_pages - $window < 0)
			{
				$llimit = 1;
			}
			else
			{
				$llimit = $total_pages - $window + 1;
			}
			$rlimit = $total_pages;
		}
		else
		{
			$llimit = $page - floor($window/2);
			$rlimit = $page + floor($window/2);
		}
	}
	if ($page>1)
	{
		$page_arr[$arr_count]['title'] = $lang['PREV'];
		$page_arr[$arr_count]['link'] = $url.$symb.'page='.($page-1);
		$page_arr[$arr_count]['current'] = 0;
		
		$arr_count++;
	}

	for ($x=$llimit;$x <= $rlimit;$x++) 
	{
		if ($x <> $page) 
		{
			$page_arr[$arr_count]['title'] = $x;
			$page_arr[$arr_count]['link'] = $url.$symb.'page='.($x);
			$page_arr[$arr_count]['current'] = 0;
		} 
		else 
		{
			$page_arr[$arr_count]['title'] = $x;
			$page_arr[$arr_count]['link'] = $url.$symb.'page='.($x);
			$page_arr[$arr_count]['current'] = 1;
		}
		
		$arr_count++;
	}
	
	if($page < $total_pages)
	{
		$page_arr[$arr_count]['title'] = $lang['NEXT'];
		$page_arr[$arr_count]['link'] = $url.$symb.'page='.($page+1);
		$page_arr[$arr_count]['current'] = 0;
		
		$arr_count++;
	}
	
	return $page_arr;
}

function pagenav2($total,$page,$perpage,$url,$posts=0,$id,$config=array(),$name='',$lang=array()) 
{
	$page_arr = array();
	$arr_count = 0;

	if($posts) 
	{
		$symb='&';
	}
	else
	{
		$symb='?';
	}
	$total_pages = ceil($total/$perpage);
	$llimit = 1;
	$rlimit = $total_pages;
	$window = 5;
	$html = '';
	if ($page<1 || !$page) 
	{
		$page=1;
	}
	
	if(($page - floor($window/2)) <= 0)
	{
		$llimit = 1;
		if($window > $total_pages)
		{
			$rlimit = $total_pages;
		}
		else
		{
			$rlimit = $window;
		}
	}
	else
	{
		if(($page + floor($window/2)) > $total_pages) 
		{
			if ($total_pages - $window < 0)
			{
				$llimit = 1;
			}
			else
			{
				$llimit = $total_pages - $window + 1;
			}
			$rlimit = $total_pages;
		}
		else
		{
			$llimit = $page - floor($window/2);
			$rlimit = $page + floor($window/2);
		}
	}
	if ($page>1)
	{	
		if($url == 'cat.php')
		{
			$page_arr[$arr_count]['title'] = $lang['PREV'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'view/'.$id.'/'.$name.'/'.($page-1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'profile.php')
		{
			$page_arr[$arr_count]['title'] = $lang['PREV'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'users/'.$id.'/'.$name.'/'.($page-1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'index.php')
		{
			$page_arr[$arr_count]['title'] = $lang['PREV'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'viewall/'.($page-1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'upcoming.php')
		{
			$page_arr[$arr_count]['title'] = $lang['PREV'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'upcoming/'.$id.'/'.$name.'/'.($page-1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'search.php')
		{
			$page_arr[$arr_count]['title'] = $lang['PREV'];
			$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?q='.$id.'&amp;page='.($page-1);
			$page_arr[$arr_count]['current'] = 0;
		}
		else
		{
			$page_arr[$arr_count]['title'] = $lang['PREV'];
			$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?id='.$id.'&amp;page='.($page-1);
			$page_arr[$arr_count]['current'] = 0;
		}
				
		$arr_count++;
	}

	for ($x=$llimit;$x <= $rlimit;$x++) 
	{
		if ($x <> $page) 
		{
			if($url == 'cat.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'view/'.$id.'/'.$name.'/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 0;
			}
			elseif($url == 'profile.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'users/'.$id.'/'.$name.'/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 0;
			}
			elseif($url == 'index.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'viewall/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 0;
			}
			elseif($url == 'upcoming.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'upcoming/'.$id.'/'.$name.'/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 0;
			}
			elseif($url == 'search.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?q='.$id.'&amp;page='.($x);
				$page_arr[$arr_count]['current'] = 0;
			}
			else
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?id='.$id.'&amp;page='.($x);
				$page_arr[$arr_count]['current'] = 0;
			}
		} 
		else 
		{
			if($url == 'cat.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'view/'.$id.'/'.$name.'/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 1;
			}
			elseif($url == 'profile.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'users/'.$id.'/'.$name.'/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 1;
			}
			elseif($url == 'index.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'viewall/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 1;
			}
			elseif($url == 'upcoming.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].'upcoming/'.$id.'/'.$name.'/'.($x).'.html';
				$page_arr[$arr_count]['current'] = 1;
			}
			elseif($url == 'search.php')
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?q='.$id.'&amp;page='.($x);
				$page_arr[$arr_count]['current'] = 1;
			}
			else
			{
				$page_arr[$arr_count]['title'] = $x;
				$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?id='.$id.'&amp;page='.($x);
				$page_arr[$arr_count]['current'] = 1;
			}
		}
		
		$arr_count++;
	}
	
	if($page < $total_pages)
	{
		if($url == 'cat.php')
		{
			$page_arr[$arr_count]['title'] = $lang['NEXT'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'view/'.$id.'/'.$name.'/'.($page+1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'profile.php')
		{
			$page_arr[$arr_count]['title'] = $lang['NEXT'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'users/'.$id.'/'.$name.'/'.($page+1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'index.php')
		{
			$page_arr[$arr_count]['title'] = $lang['NEXT'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'viewall/'.($page+1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'upcoming.php')
		{
			$page_arr[$arr_count]['title'] = $lang['NEXT'];
			$page_arr[$arr_count]['link'] = $config['site_url'].'upcoming/'.$id.'/'.$name.'/'.($page+1).'.html';
			$page_arr[$arr_count]['current'] = 0;
		}
		elseif($url == 'search.php')
		{
			$page_arr[$arr_count]['title'] = $lang['NEXT'];
			$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?q='.$id.'&amp;page='.($page+1);
			$page_arr[$arr_count]['current'] = 0;
		}
		else
		{
			$page_arr[$arr_count]['title'] = $lang['NEXT'];
			$page_arr[$arr_count]['link'] = $config['site_url'].$url.'?id='.$id.'&amp;page='.($page+1);
			$page_arr[$arr_count]['current'] = 0;
		}
		
		$arr_count++;
	}
	
	return $page_arr;
}

function modrewriteurl($url)
{
	$url = str_replace(' ','_',$url);
	$url = ereg_replace("[^[:alnum:]_]", "", $url);

	return $url;
}

function getrandnum($length)
{
	$randstr=''; 
	srand((double)microtime()*1000000); 
	$chars = array ( 'a','b','C','D','e','f','G','h','i','J','k','L','m','N','P','Q','r','s','t','U','V','W','X','y','z','1','2','3','4','5','6','7','8','9'); 
	for ($rand = 0; $rand <= $length; $rand++) 
	{ 
		$random = rand(0, count($chars) -1); 
		$randstr .= $chars[$random]; 
	}
	
	return $randstr;
}

function time_taken($time)
{
	if($time > 86400)
	{
		$days = floor($time/86400);
		$hours = floor(($time-($days*86400))/3600);
		
		if($days > 1)
		{
			$took = $days . ' days';
		}
		else
		{
			$took = $days . ' day';
		}
	}
	elseif($time > 3600)
	{
		$hours = floor(($time/60)/60);
		$mins = floor(($time-($hours*3600))/60);
		
		if($hours > 1)
		{
			$took = $hours.' hours';
		}
		else
		{
			$took = $hours.' hour';
		}
	}
	elseif($time > 60)
	{
		$mins = floor($time/60);
	
		$took = $mins . ' minutes';
	}
	else
	{
		$took = $time . ' seconds';
	}
	
	return $took;
}

function makeInt ($x,$signed=false) 
{
	if(!is_numeric($x))
	{
   		$x = intval($x);
	}
	
	if(!$x)
	{
		$x=1;
	}
	
	if(!$signed)
	{
		if($x<1)
		{
			$x=1;
		}
	}
	
	return $x;
}

function getDomain($url)
{
	$parts = parse_url($url);
	
	if(isset($parts['host']))
	{
		$parts['host'] = str_replace('www.','',$parts['host']);
	
		return $parts['host'];
	}
	else
	{
		$url = str_replace('www.','',$url);
	
		return $url;
	}
}

function getuimgpath($id,$cfolder=false,$config=array())
{
	if($config['safe'])
	{
		$path = 'images/avatars/';
	}
	else
	{
		$lsb = dechex($id & 255);
		$msb = dechex(($id >> 8 ) & 255);
		
		if (strlen($lsb)==1) {$lsb = "0$lsb";}
		if (strlen($msb)==1) {$msb = "0$msb";}
		
		if($cfolder)
		{
			if(!file_exists('images/avatars/'.$msb.'/'))
			{
				mkdir('images/avatars/'.$msb);
			}
			if(!file_exists('images/avatars/'.$msb.'/'.$lsb.'/'))
			{
				mkdir('images/avatars/'.$msb.'/'.$lsb);
			}
			if(!file_exists('images/avatars/'.$msb.'/'.$lsb.'/'.$id.'/'))
			{
				mkdir('images/avatars/'.$msb.'/'.$lsb.'/'.$id);
			}
		}
	
		$path = 'images/avatars/'.$msb.'/'.$lsb.'/'.$id.'/';
	}

	return $path;
}

function getUserAvatar($id,$config,$lookup,$avatar_info,$size='s')
{
	if($lookup)
	{
		$avatar_info = mysql_fetch_row(mysql_query("SELECT avatar FROM ".$config['db']['pre']."users WHERE user_id='".validate_input($id)."' LIMIT 1"));
	}

	if($avatar_info[0])
	{
		if($config['safe'])
		{
			$path = 'images/avatars/'.$size.$id.'.jpg';
		}
		else
		{
			$lsb = dechex($id & 255);
			$msb = dechex(($id >> 8 ) & 255);
			
			if (strlen($lsb)==1) {$lsb = "0$lsb";}
			if (strlen($msb)==1) {$msb = "0$msb";}
			
			$path = 'images/avatars/'.$msb.'/'.$lsb.'/'.$id.'/'.$size.$id.'.jpg';
		}
	}
	else
	{
		if($size == 's')
		{
			$path = 'templates/'.$config['tpl_name'].'/images/noavatar16x16.gif';
		}
		elseif($size == 'm')
		{
			$path = 'templates/'.$config['tpl_name'].'/images/noavatar48x48.gif';
		}
		else
		{
			$path = 'templates/'.$config['tpl_name'].'/images/noavatar64x64.gif';
		}
	}
	
	return $path;
}

function validate_input($input,$dbcon=true,$content='all',$maxchars=0)
{
	if(get_magic_quotes_gpc()) 
	{
		if(ini_get('magic_quotes_sybase')) 
		{
			$input = str_replace("''", "'", $input);
		} 
		else 
		{
			$input = stripslashes($input);
		}
	}
	
	if($content == 'alnum')
	{
		$input = ereg_replace("[^a-zA-Z0-9]", '', $input);
	}
	elseif($content == 'num')
	{
		$input = ereg_replace("[^0-9]", '', $input);
	}
	elseif($content == 'alpha')
	{
		$input = ereg_replace("[^a-zA-Z]", '', $input);
	}
	
	if($maxchars)
	{
		$input = substr($input,0,$maxchars);
	}

	if($dbcon)
	{
		$input = mysql_real_escape_string($input);
	}
	else
	{
		$input = mysql_escape_string($input);
	}
	
	return $input;
}

function get_tags($config,$period)
{
	$tags = array();

	if($period == 'all')
	{
		$query = "SELECT tag_phrase,count(1) AS tag_count FROM ".$config['db']['pre']."tags GROUP BY tag_phrase";
	}

	$query_result = @mysql_query ($query) OR error(mysql_error(), __LINE__, __FILE__, 0, '', '');
	while ($info = @mysql_fetch_array($query_result))
	{
		$tags[stripslashes($info['tag_phrase'])] = $info['tag_count'];
	}

	return $tags;
}

function send_email($email,$body,$subject,$config)
{
	require_once("includes/classes/class.phpmailer.php");
	
	$mail = new PHPMailer();
	
	if($config['email']['type'] == 'smtp')
	{
		$mail->IsSMTP();
		$mail->SMTPAuth = true;
		$mail->Username = $config['email']['smtp']['user'];
		$mail->Password = $config['email']['smtp']['pass'];
		$mail->Host = $config['email']['smtp']['host'];
	}
	elseif ($config['email']['type'] == 'sendmail')
	{
		$mail->IsSendmail();
	}
	else
	{
		$mail->IsMail();
	}
	
	$mail->FromName = $config['site_title'];
	$mail->From = $config['admin_email'];
	$mail->AddAddress($email);
	
	$mail->Subject = $subject;
	$mail->Body = $body;
	$mail->IsHTML(false);
	$mail->Send();
}

function parse_tags($config,$tags)
{
	$tag_return = '';

	if(trim($tags) != '')
	{
		$tag_array = explode(',',$tags);
		
		foreach ($tag_array as $key => $value)
		{
			$tag_return.= '<a href="'.$config['site_url'].'search.php?type=tags&q='.urlencode($value).'" class="storytag">'.$value.'</a> ';
		}
	}
	
	return $tag_return;
}

function check_user_group($config)
{
	$usergroup = 1;

	if(isset($_SESSION['duser']['id']))
	{
		if(!isset($_SESSION['duser']['group']))
		{
			$user_info = mysql_fetch_row(mysql_query("SELECT group_id FROM ".$config['db']['pre']."users WHERE user_id='".validate_input($_SESSION['duser']['id'])."' LIMIT 1"));
			
			if(isset($user_info[0]))
			{
				$usergroup = $user_info[0];
				
				$_SESSION['duser']['group'] = $usergroup;
			}
		}
	}
	
	$group_info = mysql_fetch_array(mysql_query("SELECT group_dig,group_cdig FROM ".$config['db']['pre']."usergroups WHERE group_id='".validate_input($usergroup)."' LIMIT 1"));
	
	return $group_info;
}

function encode_ip($HTTP_SERVER_VARS,$HTTP_ENV_VARS)
{
	if( getenv('HTTP_X_FORWARDED_FOR') != '' )
	{
		$client_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : $REMOTE_ADDR );
	
		$entries = explode(',', getenv('HTTP_X_FORWARDED_FOR'));
		reset($entries);
		while (list(, $entry) = each($entries)) 
		{
			$entry = trim($entry);
			if ( preg_match("/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/", $entry, $ip_list) )
			{
				$private_ip = array('/^0\./', '/^127\.0\.0\.1/', '/^192\.168\..*/', '/^172\.((1[6-9])|(2[0-9])|(3[0-1]))\..*/', '/^10\..*/', '/^224\..*/', '/^240\..*/');
				$found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
	
				if ($client_ip != $found_ip)
				{
					$client_ip = $found_ip;
					break;
				}
			}
		}
	}
	else
	{
		$client_ip = ( !empty($HTTP_SERVER_VARS['REMOTE_ADDR']) ) ? $HTTP_SERVER_VARS['REMOTE_ADDR'] : ( ( !empty($HTTP_ENV_VARS['REMOTE_ADDR']) ) ? $HTTP_ENV_VARS['REMOTE_ADDR'] : $REMOTE_ADDR );
	}
	
	return $client_ip;
}

function get_settings($page,$config)
{
	$settings = array();
	
	$query = "SELECT setting_id,setting_name,setting_value FROM ".$config['db']['pre']."settings WHERE setting_file='' OR setting_file='".validate_input($page)."'";
	$query_result = mysql_query ($query) OR error(mysql_error(), __LINE__, __FILE__, 0, '', '');
	while ($info = mysql_fetch_array($query_result))
	{
		$settings[$info['setting_name']] = $info['setting_value'];
	}
	
	return $settings;
}

function update_setting($config,$name,$value)
{
	mysql_query("UPDATE `".$config['db']['pre']."settings` SET `setting_value` = '".validate_input($value)."' WHERE `setting_name` = '".validate_input($name)."' LIMIT 1 ;");
}
?>